package com.zone.domain.acticity.service.quota;

import com.alibaba.fastjson.JSON;
import com.zone.domain.acticity.model.aggregate.CreateActivityOrderAggregate;
import com.zone.domain.acticity.model.entity.*;
import com.zone.domain.acticity.model.valobj.ActivityOrderTraceTypeEnum;
import com.zone.domain.acticity.model.valobj.ActivitySkuStockSubTaskVO;
import com.zone.domain.acticity.repository.IActivityRepository;
import com.zone.domain.acticity.service.ActivitySupport;
import com.zone.domain.acticity.service.IActivityOrderQuota;
import com.zone.domain.acticity.service.IActivitySkuStock;
import com.zone.domain.acticity.service.quota.policy.ITraceService;
import com.zone.domain.common.factory.SimpleFactory;
import com.zone.types.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author: zongzi
 * @description: 抽奖活动抽象类，提供统一操作 or 算法流程
 * @date: 2024/6/30
 */
@Service
@Slf4j
public class ActivityOrderQuotaImpl implements IActivityOrderQuota {
    @Autowired
    private ActivitySupport activityOrderSupport;
    @Autowired
    private IActivityRepository activityRepository;
    @Autowired
    private IActivitySkuStock activitySkuStock;

    @Override
    public final ActivityCreatedOrderResponseEntity doOrder(ActivityOrderCreateEntity createEntity) {
        // 参数校验
        Validate.notEmpty(createEntity.getUserId(), "用户不能为空!");
        Validate.notNull(createEntity.getSku(), "活动库存不能为空！");
        Validate.notEmpty(createEntity.getOutBusinessNo(), "外部单据号不能为空！");
        Validate.notNull(createEntity.getOrderTraceTypeEnum(), "订单交易类型不能为空！");

        // 返回未支付的活动流水单
        if (ActivityOrderTraceTypeEnum.PAY.getCode().equals(createEntity.getOrderTraceTypeEnum().getCode())) {
            ActivityOrderEntity noPayOrder = activityRepository.queryRecentOneMonthNoPayOrder(createEntity.getUserId(), createEntity.getSku());
            if (Objects.nonNull(noPayOrder)) {
                return ActivityCreatedOrderResponseEntity.builder()
                        .activityId(noPayOrder.getActivityId())
                        .orderId(noPayOrder.getOrderId())
                        .outBusinessNo(noPayOrder.getOutBusinessNo())
                        .productAmount(noPayOrder.getProductAmount())
                        .build();
            }
        }

        // 查询活动sku信息（校验活动信息）
        ActivitySkuEntity activitySku = activityOrderSupport.queryActivitySku(createEntity.getSku());
        if (ActivityOrderTraceTypeEnum.PAY.getCode().equals(createEntity.getOrderTraceTypeEnum().getCode())) {
            Validate.notNull(activitySku.getProductAmount(), "sku的交易金额不能为空！");
        }
        // 查询活动信息
        ActivityEntity activity = activityOrderSupport.queryActivity(activitySku.getActivityId());
        // 校验活动信息
        ActivityEntity.EffectResult effectResult = activity.takeEffect();
        if (!effectResult.isEffect()) {
            throw new BizException(effectResult.getErrorMsg());
        }
        // 查询活动次数配置信息
        ActivityCountEntity activityCount = activityOrderSupport.queryActivityCount(activitySku.getActivityCountId());
        log.info("sku = {}, activity = {}, activityCount = {}", JSON.toJSONString(activitySku), JSON.toJSONString(activity), JSON.toJSONString(activityCount));

        // 活动库存扣减
        boolean descResult = activitySkuStock.descActivitySkuStock(activitySku.getSku());
        if (!descResult) {
            throw new BizException("活动库存不足！");
        }
        // 活动库存扣减任务加入延时队列
        ActivitySkuStockSubTaskVO skuStockSubTaskVO = new ActivitySkuStockSubTaskVO();
        skuStockSubTaskVO.setSku(createEntity.getSku());
        activitySkuStock.offerActivitySkuStockSubTask(skuStockSubTaskVO);

        // 构建下单聚合对象
        CreateActivityOrderAggregate createActivityOrderAggregate = new CreateActivityOrderAggregate();
        createActivityOrderAggregate.setUserId(createEntity.getUserId());
        createActivityOrderAggregate.setSku(createEntity.getSku());
        createActivityOrderAggregate.setOutBusinessNo(createEntity.getOutBusinessNo());
        createActivityOrderAggregate.setActivityCountEntity(activityCount);
        createActivityOrderAggregate.setActivityEntity(activity);
        createActivityOrderAggregate.setActivitySku(activitySku);
        // 创建订单
        SimpleFactory<ITraceService> traceSimpleFactory = new SimpleFactory<>(ITraceService.class);
        ITraceService traceService = traceSimpleFactory.newInstance(createEntity.getOrderTraceTypeEnum().getCode());
        ActivityOrderEntity activityOrderEntity = traceService.trace(createActivityOrderAggregate);

        return ActivityCreatedOrderResponseEntity.builder()
                .activityId(activityOrderEntity.getActivityId())
                .orderId(activityOrderEntity.getOrderId())
                .outBusinessNo(activityOrderEntity.getOutBusinessNo())
                .productAmount(activityOrderEntity.getProductAmount())
                .build();
    }

    @Override
    public Integer queryUserDayRaffleCount(String userId, Long activityId) {
        return activityRepository.queryUserDayRaffleCountByActivityId(userId, activityId);
    }

    @Override
    public RaffleActivityAccountEntity queryUserActivityAccount(String userId, Long activityId) {
        return activityRepository.queryUserActivityAccount(userId, activityId);
    }
}
